import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
import { getToken, setToken, removeToken } from "@/utils/token.js";
import { Toast } from "vant";
import router from "@/router";
import JSONbig from 'json-bigint'
Vue.use(VueAxios, axios);

const instance = axios.create({
  baseURL: "http://toutiao-app.itheima.net",
  timeout: 10000,
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    try {
      return JSONbig.parse(data)
    } catch (err) {
      return data
    }

  }],
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (getToken()) {
      config.headers = { Authorization: `Bearer ${getToken().token}` };
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response;
  },
  async function (error) {
    // 对响应错误做点什么
    if (error.response.status == 401) {
      setTimeout(() => {
        console.clear();
      }, 2000);
      if (getToken()) {
        try {
          let res = await axios({
            url: "http://toutiao-app.itheima.net/v1_0/authorizations",
            method: "PUT",
            headers: { Authorization: `Bearer ${getToken().refresh_token}` }
          });
          setToken({
            refresh_token: getToken().refresh_token,
            token: res.data.data.token
          });
          return instance(error.config);
        } catch (err) {
          Toast.fail("请先登录");
          removeToken();
          router.push({ path: "/login" });
        }
      } else {
        Toast.fail("请先登录");
        removeToken();
        router.push({ path: "/login" });
      }
    }

    return Promise.reject(error);
  }
);

export default instance;
